package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.extend.WorkStatementTemplateModuleExtend;
import com.zb.mapper.ZjWorkStatementTemplateMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjWorkStatementTemplateFieldContentService;
import com.zb.service.ZjWorkStatementTemplateFieldService;
import com.zb.service.ZjWorkStatementTemplateModuleService;
import com.zb.service.ZjWorkStatementTemplateService;
import com.zb.vo.OrderModuleFieldListVo;
import com.zb.vo.TemplateModuleVo;
import com.zb.vo.WorkStatementTemplateListVo;
import com.zb.vo.WorkStatementTemplateVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单结单模板表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-10-07
 */
@Service
public class ZjWorkStatementTemplateServiceImpl extends ServiceImpl<ZjWorkStatementTemplateMapper, ZjWorkStatementTemplate> implements ZjWorkStatementTemplateService {
    @Resource
    private ZjWorkStatementTemplateMapper workStatementTemplateMapper;
    @Resource
    private ZjWorkStatementTemplateModuleService workStatementTemplateModuleService;
    @Resource
    private ZjWorkStatementTemplateFieldService workStatementTemplateFieldService;
    @Resource
    private ZjWorkStatementTemplateFieldContentService workStatementTemplateFieldContentService;

    // 新增或修改结单模板
    @Override
    @Transactional
    public void save(AccounLoginInfo loginInfo, WorkStatementTemplateVo templateVo) {
        Assert.isTrue(null == workStatementTemplateMapper.existByName(loginInfo.getCustAccId(), templateVo.getId(), templateVo.getName()), "结单模板[" + templateVo.getName() + "]已重复");
        ZjWorkStatementTemplate template = new ZjWorkStatementTemplate();
        BeanUtil.copyProperties(templateVo, template);
        template.setDisabled(templateVo.getStatus());
        template.setUpdateEmpId(loginInfo.getId());
        template.setUpdateEmp(loginInfo.getName());
        if (null != template.getId()) {
            this.updateById(template);
        } else {
            template.setId(IdWorker.getId());
            template.setCustAccId(loginInfo.getCustAccId());
            template.setCreateEmpId(loginInfo.getId());
            template.setCreateEmp(loginInfo.getName());
            this.save(template);
        }
        workStatementTemplateModuleService.save(loginInfo.getCustAccId(), template.getId(), templateVo.getTemplateModuleIds(), templateVo.getDelTemplateModuleIds());
        workStatementTemplateFieldService.save(loginInfo.getCustAccId(), template.getId(), templateVo.getTemplateField());
    }

    // 获取结单模板列表
    @Override
    public Map<String, Object> getList(Long custAccId, SelectVo selectVo) {
        PageUtil.setPageLimit(selectVo);
        QueryWrapper<ZjWorkStatementTemplate> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_update");
        wrapper.eq("cust_acc_id", custAccId);
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        Page<ZjWorkStatementTemplate> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        List<Long> ids = page.getRecords().stream().map(ZjWorkStatementTemplate::getId).toList();
        List<WorkStatementTemplateModuleExtend> moduleExtends = workStatementTemplateModuleService.getModuleByWorkStatementTemplateIds(ids);

        List<WorkStatementTemplateListVo> voList = page.getRecords().stream().map(tm -> {
            WorkStatementTemplateListVo vo = new WorkStatementTemplateListVo();
            BeanUtil.copyProperties(tm, vo);
            vo.setStatus(tm.getDisabled());
            vo.setCreateTime(tm.getGmtCreate());
            vo.setUpdateTime(tm.getGmtUpdate());
            vo.setModuleName(moduleExtends.stream().filter(f -> Objects.equals(f.getWorkStatementTemplateId(), tm.getId())).map(WorkStatementTemplateModuleExtend::getName).collect(Collectors.joining("、")));
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 根据ID获取结单模板详情
    @Override
    public WorkStatementTemplateVo getDetail(Long id) {
        ZjWorkStatementTemplate template = this.getById(id);
        Assert.isTrue(null != template, "结单模板参数ID[" + id + "]的数据不存在");

        WorkStatementTemplateVo vo = new WorkStatementTemplateVo();
        BeanUtil.copyProperties(template, vo);
        vo.setStatus(template.getDisabled());
        vo.setTemplateModuleIds(workStatementTemplateModuleService.getModuleByWorkStatementTemplateId(id).stream().map(mo -> {
            TemplateModuleVo mv = new TemplateModuleVo();
            BeanUtil.copyProperties(mo, mv);
            return mv;
        }).toList());
        vo.setTemplateField(workStatementTemplateFieldService.getByworkStatementTemplateId(id));
        return vo;
    }

    // 批量启用或禁用结单模板
    @Override
    public void updateDisabledBatchById(AccounLoginInfo loginInfo, List<Long> idList, boolean status) {
        workStatementTemplateMapper.updateDisabledBatchById(loginInfo, idList, status);
    }

    // 批量删除结单模板
    @Override
    @Transactional
    public void deleteBatchById(List<Long> ids) {
        List<Long> fieldIds = workStatementTemplateFieldService.getByworkStatementTemplateIds(ids).stream().map(ZjWorkStatementTemplateField::getId).toList();
        List<ZjWorkStatementTemplateField> relation = workStatementTemplateFieldService.getRelationByIds(fieldIds);
        if (!relation.isEmpty()) {
            List<Long> templateIds = relation.stream().map(ZjWorkStatementTemplateField::getWorkStatementTemplateId).distinct().toList();
            QueryWrapper<ZjWorkStatementTemplate> wrapper = new QueryWrapper<>();
            wrapper.select("name");
            wrapper.in("id", templateIds);
            String names = this.list(wrapper).stream().map(ZjWorkStatementTemplate::getName).collect(Collectors.joining("、"));
            Assert.isTrue(false, "结单模板[" + names + "]下的字段参数[" + relation.stream().map(ZjWorkStatementTemplateField::getName).collect(Collectors.joining("、")) + "]已被使用，不可删除");
        }
        workStatementTemplateModuleService.deleteBatchByWorkStatementTemplateIds(ids);
        workStatementTemplateFieldService.deleteBatchByWorkStatementTemplateIds(ids);
        this.removeByIds(ids);
    }

    // 根据工单模块ID获取结单模块字段列表
    @Override
    public Map<String, Object> getModuleField(Long moduelId, SelectVo selectVo) {
        PageUtil.setPageLimit(selectVo);
        List<ZjWorkStatementTemplateModule> templateModules = workStatementTemplateModuleService.getByModuleId(moduelId);
        if (CollectionUtils.isEmpty(templateModules)) {
            return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), 0L, new ArrayList<>());
        }
        List<Long> templateIds = templateModules.stream().map(ZjWorkStatementTemplateModule::getWorkStatementTemplateId).distinct().toList();

        QueryWrapper<ZjWorkStatementTemplate> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        wrapper.in("id", templateIds);
        List<ZjWorkStatementTemplate> templateList = this.list(wrapper);

        QueryWrapper<ZjWorkStatementTemplateField> fieldQueryWrapper = new QueryWrapper<>();
        fieldQueryWrapper.in("work_statement_template_id", templateIds);
        if (StringUtils.isNotBlank(selectVo.getName())) {
            fieldQueryWrapper.like("name", selectVo.getName());
        }
        Page<ZjWorkStatementTemplateField> page = workStatementTemplateFieldService.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), fieldQueryWrapper);
        List<Long> fieldIds = page.getRecords().stream().map(ZjWorkStatementTemplateField::getId).toList();
        List<ZjWorkStatementTemplateFieldContent> contentList = workStatementTemplateFieldContentService.getByWorkStatementTemplateFieldIds(fieldIds);

        List<OrderModuleFieldListVo> voList = page.getRecords().stream().map(tem -> {
            OrderModuleFieldListVo vo = new OrderModuleFieldListVo();
            BeanUtil.copyProperties(tem, vo);
            vo.setUpdateTime(tem.getGmtUpdate());
            vo.setTemplate(templateList.stream().filter(f -> Objects.equals(f.getId(), tem.getWorkStatementTemplateId())).map(ZjWorkStatementTemplate::getName).findFirst().orElse(""));
            vo.setContent(contentList.stream().filter(f -> Objects.equals(f.getWorkStatementTemplateFieldId(), tem.getId())).map(ZjWorkStatementTemplateFieldContent::getVal).collect(Collectors.joining("、")));
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 根据结单ID查询结单模板信息
    @Override
    public List<ZjWorkStatementTemplate> getByIds(List<Long> ids) {
        if (null == ids || ids.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkStatementTemplate> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        wrapper.in("id", ids);
        return this.list(wrapper);
    }

    // 获取结单模板下拉数据
    @Override
    public Map<String, Object> getOrderFinishTemplateSelect(Long custAccId, SelectVo selectVo) {
        PageUtil.setSelectPageLimit(selectVo);
        QueryWrapper<ZjWorkStatementTemplate> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name")
                .eq("cust_acc_id", custAccId)
                .eq("is_disabled", false);
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        Page<ZjWorkStatementTemplate> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords().stream().map(tem -> {
            return new SelectResultVo(tem.getId(), tem.getName());
        }).toList());
    }
}
